package cn.kgc.filter;

import cn.kgc.constant.GateWayConstant;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.logging.Filter;

/**
 * <p></p>
 *
 * @author 李孟鸠
 * @Date: 2022年12月02日11:44
 */
@Component
public class GlobalCachedRequestBodyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        //获得请求地址
        String uri = serverHttpRequest.getURI().toString();
        //如果请求是登录或者注册请求，可以将请求直接放行
        boolean loginOrRegister=
                uri.contains(GateWayConstant.LOGIN_URL)
                        ||
                        uri.contains(GateWayConstant.REGISTER_URL);
        //如果是登录或者注册请求，直接放行
        if(!loginOrRegister || serverHttpRequest.getHeaders().getContentType()==null){
            return chain.filter(exchange);//直接放行
        }

        //如果请求中没有参数，请求也可以直接放行

        //其他的请求进行处理:获得原来的请求中的参数的副本，根据副本创建ServerHttpRequest对象，
        // 请求放行时，封装的是上一步创建的ServerHttpRequest对象

        return DataBufferUtils.join(serverHttpRequest.getBody()).flatMap(dataBuffer->{
           //处理dataBuffer时，dataBuffer不能被释放
            DataBufferUtils.retain(dataBuffer);
            Flux<DataBuffer> flux = Flux.defer(() -> {
                return Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount()));
            });
            //请求体的副本创建新的serverHttpRequest2对象
                ServerHttpRequest serverHttpRequest2=new ServerHttpRequestDecorator(serverHttpRequest){
                    @Override
                    public Flux<DataBuffer> getBody() {
                        return flux;
                    }
                };
                //请求放行
                return chain.filter(exchange.mutate().request(serverHttpRequest2).build());
        });
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
